<template>
	<BaseContainer>
		<aplid-base-crud ref="crud" class="w-100" v-bind="{...baseConfig,...$attrs}" :operateFormate="operateFormate"> </aplid-base-crud>
		<el-dialog v-model="visible" title="调度介入" width="500">
			<AplidForm v-bind="dispatchConfig" v-model="formModel" @submit="onSubmit"></AplidForm>
		</el-dialog>

    <el-dialog v-model="visibleTrtc" top="5vh" title="视频通话" width="65%" :close-on-click-modal="false">
      <TrtcPage v-if="visibleTrtc" :roomId="roomId" @refresh="onRefresh"></TrtcPage>
		</el-dialog>
	</BaseContainer>
</template>

<script setup lang="ts">
import { baseConfig, dispatchConfig } from './config'
import apiMod from '@/apiMod/index'
import {getStore} from '@/utils/store'
import { ElMessage, ElMessageBox } from 'element-plus'
import TrtcPage from './TrtcPage/index.vue'
import useMqtt from '@/hooks/useMqttHooks'

const crud = ref(null)
const visible = ref(false)
const visibleTrtc = ref(false)
const formModel:any = ref({})
const userInfo = getStore('userInfo')||{}
const nowRowData:any = ref({})
const { doPublish } = useMqtt()
const roomId = ref('')
const operateFormate = (form, type) => {
  nowRowData.value = form
	return new Promise((resolve, reject) => {
		if (type == 'dispatch') {
			visible.value = true
		} else {
			resolve(form)
		}
	})
}

const onRefresh = ()=> {
  visibleTrtc.value = false
}

const openTrtc = (queryObj) => {
  ElMessageBox.confirm(
    '和调度员视频通话, 是否发起?',
    '提示',
    {
      confirmButtonText: '发起视频通话',
      cancelButtonText: '不用了',
      type: 'warning',
    }
  )
    .then(() => {
     roomId.value= `${queryObj.staffId}_${nowRowData.value.id}_${nowRowData.value.alarmReason}_${nowRowData.value.creditCode}`
     // 发送mqtt 通知用户接听
      doPublish('trtc_video_call',JSON.stringify({
        ...queryObj,
        userId:userInfo.id,
        userName:userInfo.realName,
        organizationId:userInfo.organizationId,
        roomId:roomId.value
      }))
      visibleTrtc.value = true 
    })
    .catch(() => {
     crud.value?.refresh()
    })
}

const onSubmit = (form, done) => {
  const queryObj = {
...form,
      fromId:nowRowData.value.id,
      alarmReason:nowRowData.value.alarmReason,
      alarmReasonLabel:nowRowData.value.alarmReasonLabel,
      creditCode:userInfo.organizationId,
      organizationId:userInfo.organizationId,
      organizationName:userInfo.organizationName,
      dispatchType:2,
      dispatchTypeLabel:'调度',
      fromType:1,
  }
	apiMod
		.view_pbDispatch_add(queryObj)
		.then(res => {
			visible.value = false
      ElMessage.success('操作成功!')
      openTrtc({
        ...queryObj,
        id:res.data
      })
			done()
		})
		.catch(() => {
			done()
		})
}
</script>

<style lang="scss" scoped></style>
